package com.mark.tool.randomalgorithm;
import java.util.List;
import java.util.Random;

import com.mark.tool.constant.WeightCategory;

/**
 * 带有权重的随机算法
 * @author maliqiang
 * @since 2016年12月1日
 * @version 1.0
 *
 */
public class WeightRandom {
	private static Random random = new Random();

	
	/**
	 * 按照权重分组
	 * @param categorys 权重对象WeightCategory的列表
	 * @return
	 */
	public static String groupUser(List<WeightCategory> categorys) {
		Integer weightSum = 0;
		String result = "";
		for (WeightCategory wc : categorys) {
			weightSum += wc.getWeight();
		}

		if (weightSum <= 0) {
			System.err.println("Error: weightSum=" + weightSum.toString());
			return "权重总和为0";
		}
		Integer n = random.nextInt(weightSum); // 在权重总和中取随机数
		Integer m = 0;
		for (WeightCategory wc : categorys) {
			if (m <= n && n < m + wc.getWeight()) {
				System.out.println("This Random Category is "
						+ wc.getCategory());
				result = wc.getCategory();
				break;
			}
			m += wc.getWeight();
		}
		return result;

	}

	

}
